package com.wyc.blog.aspcet;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @ClassName LogAspect
 * @Author 王韫琛
 * @Date 2021/4/9 9:20
 * @Version 1.0
 */
@Aspect//可以进行切面的操作
@Component//开启组件扫描
public class LogAspect {
    //日志记录器
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * @Pointcut():声明log是一个切面
     * execution():来规定切面拦截那些了类
     *  * com.wyc.blog.web.*.*(..):任何参数的任何方法，所有的类里面
     */
    @Pointcut("execution(* com.wyc.blog.web.*.*(..))")
    public void  log(){}

    /**
     * @Before("log()"): log()方法会在之前执行
     */
    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURI();
        String ip = request.getRemoteAddr();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName();
        //获取请求参数
        Object[] args = joinPoint.getArgs();
        //构造对象
        RequestLog requestLog = new RequestLog(url,ip,classMethod,args);
        //记录的请求
        logger.info("Request : {}",requestLog);
    }

    /**
     * @After("log()"): log()方法之后执行
     */
    @After("log()")
    public  void doAfter(){
        //logger.info("--------------------doAfter--------------------");
    }

    @AfterReturning(returning = "result",pointcut = "log()")
    public void doAfterReturn(Object result){
        logger.info("Result : {}",result);
    }
    private class RequestLog{
        //路径
        private String url;
        //ip
        private String ip;
        //调用那个类的那个方法
        private String classMethod;
        //请求参数
        private Object[] args;

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "RequestLog{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }
}
